# -*- coding: utf_8 -*-
# @Create   : 2021/10/25 18:38
# @Author   : Neymar
# @Remark   : 时间处理
import time
from datetime import datetime,timedelta
from utils.parser.fields import check_time_str


class TimeProcess(object):
    def __init__(self,):
        self.week_list = []  # 一周日期列表
        self.horizon = []    # 一周时间戳范围

    def get_week(self,timestamp: float ) -> list:
        """
        获取指定时间一周内的日期列表
        param: timestamp 需要查的时间戳
        return: self.week_list 一周日期列表
        example:
            self.week_list: ['2021-11-08','2021-11-09','2021-11-10','2021-11-11','2021-11-12','2021-11-13','2021-11-14']
        """
        date = datetime.utcfromtimestamp(timestamp)
        week_day = date.weekday()

        start_day = date - timedelta(week_day)
        for i in range(7):
            wd = start_day + timedelta(i)
            self.week_list.append(wd.strftime('%Y-%m-%d'))
        return self.week_list

    def stamp_horizon(self,timestamp: float) -> list:
        """
        获取一周的时间戳范围
        param: timestamp 需要查的时间戳
        return: self.horizon 一周的时间戳范围
        example:
            self.horizon: [1636300800,1636905599]
        """
        if not self.week_list:
            self.get_week(timestamp)
        start_time = self.week_list[0]+' 00:00'
        end_time = self.week_list[-1] + ' 23:59'
        start_time = check_time_str(start_time)
        end_time = check_time_str(end_time) + 59
        self.horizon = [start_time, end_time]
        return self.horizon

    def get_every_day(self, timestamp: float) -> list:
        """
        根据一周的时间戳范围获取一周内每一天的时间戳范围
        param: timestamp 需要查的时间戳
        return: every_day_list 一周的七天的时间戳范围
        example:
            every_day_list: [[1636300800,*],[*，*],[*，*],[*，*],[*，*],[*，*],[*,1636905599]]
        """
        if not self.horizon:
            self.stamp_horizon(timestamp)
        every_day_list = []
        for i in range(7):
            day_start_time = self.horizon[0] + 86400 * i
            every_day_list.append([day_start_time,day_start_time+86399])
        return every_day_list


def stamp_2_date(stamp: float) -> str:
    """
    时间戳转换为 “Y-m-d H:M”格式
    param: stamp 需要转换的时间戳
    return: data_str “Y-m-d H:M”
    """
    try:
        # date = datetime.utcfromtimestamp(stamp)
        date = time.localtime(stamp)
        date_str = time.strftime('%Y-%m-%d %H:%M',date)
    except ValueError:
        raise AssertionError('时间戳范围有误，您的时间戳：%s' % stamp)
    return date_str



